package com.zhang.first.day03;

import com.zhang.first.utils.IntegerSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.scala.typeutils.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: ValueState值状态
 * @author: zhang
 * @date: 2022/1/16 15:45
 */
public class Example10 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerStatistic>() {
                    //定义状态
                    //每个key维护自己状态变量
                    //状态变量是一个单例，只能初始化一次
                    private ValueState<IntegerStatistic> valueState;

                    //初始化状态
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //初始化了一个空累加器
                        valueState = getRuntimeContext().getState(
                                //acc表示状态变量在在状态后端里的名字
                                new ValueStateDescriptor<IntegerStatistic>("acc", Types.POJO(IntegerStatistic.class))
                        );
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntegerStatistic>.Context ctx, Collector<IntegerStatistic> out) throws Exception {
                        // 第一条数据到达
                        // .update更新状态变量
                        if (valueState.value() == null) {
                            valueState.update(
                                    new IntegerStatistic(
                                            value,
                                            value,
                                            value,
                                            1,
                                            value
                                    )
                            );
                        } else {
                            //输入数据和累加器聚合
                            IntegerStatistic tmp = valueState.value();
                            IntegerStatistic newACC = new IntegerStatistic(
                                    Math.max(tmp.max, value),
                                    Math.min(tmp.min, value),
                                    tmp.sum + value,
                                    tmp.count + 1,
                                    (tmp.sum + value) / (tmp.count + 1)
                            );
                            //更新累加器
                            valueState.update(newACC);
                        }
                        //输出累加器
                        out.collect(valueState.value());
                    }
                })
                .print();


        env.execute();
    }

    //第一POJO CLASS
    public static class IntegerStatistic {
        public Integer max;
        public Integer min;
        public Integer sum;
        public Integer count;
        public Integer avg;

        public IntegerStatistic() {
        }

        public IntegerStatistic(Integer max, Integer min, Integer sum, Integer count, Integer avg) {
            this.max = max;
            this.min = min;
            this.sum = sum;
            this.count = count;
            this.avg = avg;
        }

        @Override
        public String toString() {
            return "IntegerStatistic{" +
                    "max=" + max +
                    ", min=" + min +
                    ", sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    '}';
        }
    }
}
